package com.whacos.modules.system.controller;

import com.whacos.common.controller.BaseController;
import com.whacos.common.vo.ResponseVO;
import com.whacos.modules.system.entity.SysUserOnline;
import com.whacos.modules.system.service.SessionService;
import com.whacos.modules.system.vo.SysUserOnlineVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author xiongdun
 * @description SessionController
 * @since 2018/11/17 17:11
 */
@RequestMapping("/sys/online")
@Controller
@Slf4j
public class SessionController extends BaseController {

    @Autowired
    private SessionService sessionService;

    @GetMapping()
    public String online() {
        return "sys/online/online";
    }

    // @Log("查询在线用户")
    @ResponseBody
    @GetMapping("/list")
    public List<SysUserOnlineVO> list() {
        // 查询数据
        List<SysUserOnline> sysUserOnlineList = sessionService.list();
        List<SysUserOnlineVO> sysUserOnlineVOList = new ArrayList<>();

        // 返回结果
        sysUserOnlineList.forEach(sysUserOnline -> {
            SysUserOnlineVO sysUserOnlineVO = new SysUserOnlineVO();
            BeanUtils.copyProperties(sysUserOnline, sysUserOnlineVO);
            sysUserOnlineVOList.add(sysUserOnlineVO);
        });
        return sysUserOnlineVOList;
    }

    // @Log("强制退出在线用户")
    @ResponseBody
    @GetMapping("/forceLogout/{sessionId}")
    public ResponseVO forceLogout(@PathVariable("sessionId") String sessionId, RedirectAttributes redirectAttributes) {
        try {
            this.sessionService.forceLogout(sessionId);
            return ResponseVO.success();
        } catch (Exception e) {
            log.error("强制用户退出登陆异常，异常原因：" + e.getMessage(), e);
            return ResponseVO.error();
        }

    }

    // @Log("获取在线用户 sessionList")
    @ResponseBody
    @GetMapping("/sessionList")
    public Collection<Session> sessionList() {
        return sessionService.sessionList();
    }
}
